package com.hcloud.auth.audit.service;

import com.hcloud.audit.api.event.LoginLogEvent;
import com.hcloud.audit.core.bean.LoginLog;
import com.hcloud.audit.core.util.IPUtils;
import com.hcloud.common.core.util.SpringUtil;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Auther hepangui
 * @Date 2018/11/20
 */
@Service
public class LoginLogService {
    private void saveLoginLog(String account, String username, boolean success, String msg) {

        try {
            var request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            var userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
            var bean = LoginLog.builder().username(username)
                    .account(account).ipAddr(IPUtils.getIpAddr(request))
                    .browser(userAgent.getBrowser().getName())
                    .msg(msg)
                    .device(userAgent.getOperatingSystem().getName())
                    .osName(userAgent.getOperatingSystem().getDeviceType().getName())
                    .success(success ? 1 : 0).build();
            SpringUtil.publishEvent(new LoginLogEvent(bean));
        } catch (Exception e) {
        }
    }

    public void saveSuccessLog(String account, String username) {
        this.saveLoginLog(account, username, true, "");
    }

    public void saveErrorLog(String account, String msg) {
        this.saveLoginLog(account, "", false, msg);
    }
}
